package pt.inescid.components.policyengine.heimdall.pdp.base;

import java.util.Vector;

import pt.inescid.components.policyengine.heimdall.commons.Utilities;
import pt.inescid.components.policyengine.heimdall.pap.base.EventFieldDefinition;

public class EventFieldInstance extends SimpleInstance {

	private EventFieldDefinition definition = null;
	
	private PolicyInstance currentPolicy = null; 
	
	
//  ----------------------------------------------------------
//  ------------------------   constructor   ------------------------
//  ----------------------------------------------------------
	public EventFieldInstance(EventFieldDefinition definition,
			ModelInstance currentModel, 
			PolicyInstance currentPolicy) {
		super(definition, currentPolicy);
		this.definition = definition;
		this.currentPolicy = currentPolicy;

		int fieldId = definition.getModelDef().getFieldId( 
				definition.getValue());		
		fieldId = Integer.parseInt(definition.getValue().substring(1));
		
		if (fieldId != Utilities.UNDEFINED_INT_VALUE) {
			value = currentModel.getCe().getField(fieldId).getValue();
		}
		else {
			value = null;
		}
		
	}

	
	
	
//  ----------------------------------------------------------
//  ------------------------   evaluate   ------------------------
//  ----------------------------------------------------------
	public Object evaluate(ModelInstance currentModel, boolean onlyCached) {
		
		// check if the value comes from a quantifier
		if (currentPolicy != null) {
			Vector allQuantifiers = currentPolicy.getQuantifiers();			
			QuantifierInstance currentQt = null;
			for (int i = 0; i < allQuantifiers.size(); i++) {
				currentQt = (QuantifierInstance) allQuantifiers.elementAt(i);								
				if (currentQt.hasThisVariable(definition.getValue())) {
					return (currentQt.getCurrentEvent().getField(
							definition.getModelDef().getFieldId(
							definition.getValue())).getValue());
				}
			}
		}
		
		// check if the value comes from a reevaluation instance
		if (definition.getValue().startsWith("stopCe")) {
			value = currentModel.getCe().
					getField(
							definition.getModelDef().getFieldId(
							definition.getValue())).getValue();
		}
			
		return (value);
		
	} // evaluate

}; // EventFieldInstance
